package cn.edu.seig.textbook.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class SecurityCaptchaFilter extends OncePerRequestFilter {

    private static final String defaultFilterProcessUrl = "/login";

    private static final String method = "POST";
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws  IOException, ServletException {
        if (method.equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())){
            String vcode = request.getParameter("code");
            System.out.println("vcode==="+vcode);
            String kaptcha = (String) request.getSession().getAttribute("verifyCode");
            System.out.println("randStr==="+kaptcha);
            if(!vcode.equalsIgnoreCase(kaptcha)){
                //throw new RuntimeException("验证码错误！");
                System.out.println("{success:false,code:403,message:'验证码错误'}");
                request.getSession().setAttribute("msg","验证码错误");
                //request.setAttribute("msg", "验证码错误！");
                //request.getRequestDispatcher(request.getContextPath() + "/login").forward(request,response);
                //response.setHeader("refresh", "1;url='/login'");
                response.sendRedirect("/login");
                return;
            }else
              request.getSession().removeAttribute("verifyCode");
        }
        filterChain.doFilter(request,response);
    }
}
